using System;
using System.Collections.Generic;
using System.Data;
using ExcelTemplateEngine.Models.TemplateModels;

namespace ExcelTemplateEngine.Tests.Helpers
{
    /// <summary>
    /// 测试数据生成器 - 为单元测试和集成测试生成各种测试数据
    /// </summary>
    public static class TestDataGenerator
    {
        #region 模板单元格节点数据
        
        /// <summary>
        /// 创建简单的模板单元格节点
        /// </summary>
        public static TemplateCellNode CreateSimpleTemplateNode(string address, string? expression = null)
        {
            return new TemplateCellNode(address)
            {
                RawValue = expression ?? $"Sample content for {address}",
                Expression = expression,
                IsDataBindingCell = !string.IsNullOrEmpty(expression)
            };
        }
        
        /// <summary>
        /// 创建数据绑定的模板单元格节点
        /// </summary>
        public static TemplateCellNode CreateDataBindingNode(string address, string dataSource, string fieldName)
        {
            var expression = $"{{{{{dataSource}.{fieldName}}}}}";
            return new TemplateCellNode(address)
            {
                RawValue = expression,
                Expression = expression,
                IsDataBindingCell = true,
                DataSourcePath = dataSource,
                FieldName = fieldName,
                ExpansionType = ExpansionType.Single
            };
        }
        
        /// <summary>
        /// 创建集合扩展的模板单元格节点
        /// </summary>
        public static TemplateCellNode CreateCollectionNode(string address, string dataSource, string fieldName, 
            ExpansionDirection direction = ExpansionDirection.Vertical)
        {
            var expression = $"{{{{{dataSource}.{fieldName}}}}}";
            var node = new TemplateCellNode(address)
            {
                RawValue = expression,
                Expression = expression,
                IsDataBindingCell = true,
                DataSourcePath = dataSource,
                FieldName = fieldName,
                ExpansionType = ExpansionType.Collection,
                ExpansionDirection = direction
            };
            
            // 添加一些扩展属性
            node.Properties["Context"] = "List";
            node.Properties["Sort"] = "Asc";
            
            return node;
        }
        
        /// <summary>
        /// 创建具有多重父节点关系的节点
        /// </summary>
        public static (TemplateCellNode root, TemplateCellNode child) CreateCrossExpansionNodes()
        {
            var root = CreateSimpleTemplateNode("A1", "{{ds.Header}}");
            var child = CreateCollectionNode("B2", "ds", "Item");
            
            // 设置多重父节点关系
            child.UpperParent = CreateDataBindingNode("B1", "ds", "ColumnHeader");
            child.LeftParent = CreateDataBindingNode("A2", "ds", "RowHeader");
            child.Parent = root;
            
            root.AddChild(child);
            
            return (root, child);
        }
        
        #endregion
        
        #region 测试数据源
        
        /// <summary>
        /// 创建简单的对象数据源
        /// </summary>
        public static List<Person> CreatePersonList(int count = 5)
        {
            var persons = new List<Person>();
            var random = new Random(42); // 固定种子确保测试结果可重现
            
            for (int i = 1; i <= count; i++)
            {
                persons.Add(new Person
                {
                    Id = i,
                    Name = $"Person{i}",
                    Age = 20 + random.Next(40),
                    Email = $"person{i}@example.com",
                    Salary = 30000 + random.Next(70000),
                    HireDate = DateTime.Now.AddDays(-random.Next(1000)),
                    IsActive = random.NextDouble() > 0.2
                });
            }
            
            return persons;
        }
        
        /// <summary>
        /// 创建分层数据源（部门-员工）
        /// </summary>
        public static List<Department> CreateDepartmentList()
        {
            return new List<Department>
            {
                new Department
                {
                    Name = "技术部",
                    Code = "TECH",
                    Employees = new List<Person>
                    {
                        new Person { Id = 1, Name = "张三", Age = 28, Email = "zhangsan@tech.com", Salary = 50000 },
                        new Person { Id = 2, Name = "李四", Age = 32, Email = "lisi@tech.com", Salary = 60000 }
                    }
                },
                new Department
                {
                    Name = "销售部",
                    Code = "SALES",
                    Employees = new List<Person>
                    {
                        new Person { Id = 3, Name = "王五", Age = 26, Email = "wangwu@sales.com", Salary = 45000 },
                        new Person { Id = 4, Name = "赵六", Age = 30, Email = "zhaoliu@sales.com", Salary = 48000 }
                    }
                }
            };
        }
        
        /// <summary>
        /// 创建DataTable数据源
        /// </summary>
        public static DataTable CreateDataTable(string tableName = "TestTable")
        {
            var table = new DataTable(tableName);
            
            // 添加列
            table.Columns.Add("Id", typeof(int));
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Value", typeof(decimal));
            table.Columns.Add("Date", typeof(DateTime));
            table.Columns.Add("IsActive", typeof(bool));
            
            // 添加数据
            for (int i = 1; i <= 5; i++)
            {
                table.Rows.Add(i, $"Item{i}", i * 100.5m, DateTime.Now.AddDays(i), i % 2 == 0);
            }
            
            return table;
        }
        
        /// <summary>
        /// 创建DataSet数据源
        /// </summary>
        public static DataSet CreateDataSet()
        {
            var dataSet = new DataSet("TestDataSet");
            
            // 添加主表
            var masterTable = CreateDataTable("Master");
            dataSet.Tables.Add(masterTable);
            
            // 添加详细表
            var detailTable = new DataTable("Detail");
            detailTable.Columns.Add("MasterId", typeof(int));
            detailTable.Columns.Add("DetailId", typeof(int));
            detailTable.Columns.Add("Description", typeof(string));
            detailTable.Columns.Add("Amount", typeof(decimal));
            
            for (int masterId = 1; masterId <= 3; masterId++)
            {
                for (int detailId = 1; detailId <= 3; detailId++)
                {
                    detailTable.Rows.Add(masterId, detailId, $"Detail {masterId}-{detailId}", masterId * detailId * 10.0m);
                }
            }
            
            dataSet.Tables.Add(detailTable);
            
            // 创建关系
            var relation = new DataRelation("MasterDetail",
                masterTable.Columns["Id"]!,
                detailTable.Columns["MasterId"]!);
            dataSet.Relations.Add(relation);
            
            return dataSet;
        }
        
        #endregion
        
        #region 测试样式数据
        
        /// <summary>
        /// 创建默认样式
        /// </summary>
        public static FullCellStyle CreateDefaultStyle()
        {
            return new FullCellStyle();
        }
        
        /// <summary>
        /// 创建标题样式
        /// </summary>
        public static FullCellStyle CreateHeaderStyle()
        {
            var style = new FullCellStyle();
            style.Font.Bold = true;
            style.Font.Size = 14;
            style.Fill.Type = FillType.Solid;
            style.Alignment.Horizontal = HorizontalAlignment.Center;
            return style;
        }
        
        /// <summary>
        /// 创建数据样式
        /// </summary>
        public static FullCellStyle CreateDataStyle()
        {
            var style = new FullCellStyle();
            style.Font.Size = 12;
            style.Alignment.Horizontal = HorizontalAlignment.Left;
            style.Border.Bottom = BorderStyle.Thin;
            return style;
        }
        
        #endregion
        
        #region 复杂测试场景
        
        /// <summary>
        /// 创建交叉扩展测试数据
        /// </summary>
        public static CrossExpansionTestData CreateCrossExpansionTestData()
        {
            return new CrossExpansionTestData
            {
                Headers = new[] { "Q1", "Q2", "Q3", "Q4" },
                RowLabels = new[] { "产品A", "产品B", "产品C" },
                Data = new decimal[,]
                {
                    { 100, 120, 110, 130 },
                    { 80, 90, 95, 105 },
                    { 60, 65, 70, 75 }
                }
            };
        }
        
        /// <summary>
        /// 创建分页测试数据
        /// </summary>
        public static PagedTestData CreatePagedTestData(int totalItems = 100, int pageSize = 10)
        {
            var allItems = new List<string>();
            for (int i = 1; i <= totalItems; i++)
            {
                allItems.Add($"Item {i:D3}");
            }
            
            return new PagedTestData
            {
                AllItems = allItems,
                PageSize = pageSize,
                TotalPages = (int)Math.Ceiling((double)totalItems / pageSize)
            };
        }
        
        #endregion
    }
    
    #region 测试数据模型
    
    /// <summary>
    /// 测试用的人员类
    /// </summary>
    public class Person
    {
        public int Id { get; set; }
        public string Name { get; set; } = string.Empty;
        public int Age { get; set; }
        public string Email { get; set; } = string.Empty;
        public decimal Salary { get; set; }
        public DateTime HireDate { get; set; }
        public bool IsActive { get; set; }
    }
    
    /// <summary>
    /// 测试用的部门类
    /// </summary>
    public class Department
    {
        public string Name { get; set; } = string.Empty;
        public string Code { get; set; } = string.Empty;
        public List<Person> Employees { get; set; } = new();
    }
    
    /// <summary>
    /// 交叉扩展测试数据
    /// </summary>
    public class CrossExpansionTestData
    {
        public string[] Headers { get; set; } = Array.Empty<string>();
        public string[] RowLabels { get; set; } = Array.Empty<string>();
        public decimal[,] Data { get; set; } = new decimal[0, 0];
    }
    
    /// <summary>
    /// 分页测试数据
    /// </summary>
    public class PagedTestData
    {
        public List<string> AllItems { get; set; } = new();
        public int PageSize { get; set; }
        public int TotalPages { get; set; }
        
        public List<string> GetPage(int pageNumber)
        {
            var startIndex = (pageNumber - 1) * PageSize;
            var count = Math.Min(PageSize, AllItems.Count - startIndex);
            return AllItems.GetRange(startIndex, count);
        }
    }
    
    #endregion
}